package com.heima.wemedia.builder;

import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import lombok.Data;
import org.springframework.beans.BeanUtils;

import java.util.Date;

/**
 * 构建者
 *  用构建ArticleDto对象
 */
@Data
public class ArticleDtoBulider {

    private ArticleDto articleDto = new ArticleDto();
    private WmNews wmNews;
    private WmChannelMapper wmChannelMapper;
    private WmUserMapper wmUserMapper;


    public static ArticleDtoBulider builder(WmNews wmNews, WmChannelMapper wmChannelMapper, WmUserMapper wmUserMapper){
        ArticleDtoBulider bulider = new ArticleDtoBulider();
        bulider.setWmChannelMapper(wmChannelMapper);
        bulider.setWmNews(wmNews);
        bulider.setWmUserMapper(wmUserMapper);
        return bulider;
    }

    public ArticleDtoBulider basicCopy(){
        BeanUtils.copyProperties(wmNews, articleDto);
        return this;
    }

    public ArticleDtoBulider buildWmChannel(){
        WmChannel wmChannel = wmChannelMapper.selectById(articleDto.getChannelId());
        if(wmChannel != null){
            articleDto.setChannelName(wmChannel.getName());
        }
        return this;
    }

    public ArticleDtoBulider buildWmUser(){
        //作者
        articleDto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser != null){
            articleDto.setAuthorName(wmUser.getName());
        }

        return this;
    }

    public ArticleDtoBulider buildBasic(){
        articleDto.setLayout(wmNews.getType());
        articleDto.setCreatedTime(new Date());
        articleDto.setCollection(0);
        articleDto.setComment(0);
        articleDto.setViews(0);
        articleDto.setLikes(0);
        if(wmNews.getArticleId() != null){
            articleDto.setId(wmNews.getArticleId());
        }

        return this;
    }

    public ArticleDto build(){
        return articleDto;
    }
}
